package org.soulraven.games.memory.ui.game;

import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;

import org.soulraven.games.memory.model.Card;
import org.soulraven.games.memory.util.ImageUtil;

public class ButtonCard extends JButton implements DisplayableCard {

	private static final long serialVersionUID = 2078809639049765797L;

	private ActionListener listener;
	private static final ImageIcon DECK_IMAGE;
	static {
		DECK_IMAGE = ImageUtil.getDeckImage();
	}

	private ImageIcon image;
	private Card card;

	public ButtonCard(final Card card) {
		this.card = card;
		this.image = ImageUtil.getImage(card.getNumber());
		initialize();
	}

	private void initialize() {
		this.setIcon(DECK_IMAGE);
		this.setHidden(Boolean.TRUE);
		this.setSize(DECK_IMAGE.getIconHeight(), DECK_IMAGE.getIconWidth());
		this.setPreferredSize(getSize());
	}

	/**
	 * @return the image
	 */
	public ImageIcon getImage() {
		return image;
	}

	/**
	 * @return the card
	 */
	public Card getCard() {
		return card;
	}

	@Override
	public int getNumber() {
		return card.getNumber();
	}

	@Override
	public boolean isHidden() {
		return card.isHidden();
	}

	@Override
	public void setHidden(final boolean hidden) {
		this.setIcon(hidden ? DECK_IMAGE : image);
		card.setHidden(hidden);
	}

	@Override
	public boolean isSelectable() {
		return card.isSelectable();
	}

	public void addActionListener(final ActionListener listener) {
		this.listener = listener;
		super.addActionListener(listener);
	}

	@Override
	public void setSelectable(final boolean selectable) {
		card.setSelectable(selectable);
		if (!selectable) {
			super.removeActionListener(this.listener);
		}
		else {
			super.addActionListener(listener);
		}
	}

	@Override
	public String toString() {
		return card.toString();
	}
}
